﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OOAD_Project_Engine.Domain.Entities;
using OOAD_Project_Engine.Domain.Factories;
using Microsoft.Xna.Framework;

namespace OOAD_Project_Engine.Application.Services
{
    public class SceneComponent : DrawableGameComponent, ISceneService
    {
        ComponentManager manager;
        EntityFactory factory;

        public SceneComponent(Game game)
            : base(game)
        {
            manager = new ComponentManager();
            factory = new EntityFactory(manager);
            Game.Components.ComponentAdded += this.OnComponentAdded;
            Game.Components.ComponentRemoved += this.OnComponentRemoved;
        }

        public ComponentManager Manager { get { return manager; } }

        public EntityFactory Factory { get { return factory; } }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            manager.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            manager.Draw(gameTime);
        }

        protected override void LoadContent()
        {
            base.LoadContent();
            manager.LoadContent();
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();
            manager.UnloadContent();
        }

        public void OnComponentAdded(object sender, GameComponentCollectionEventArgs e)
        {
            if (e.GameComponent == this)
            {
                if (Game.Services.GetService(typeof(ISceneService)) != null)
                {
                    throw new ArgumentException("EntityManagerComponent already present.");
                }
                Game.Services.AddService(typeof(ISceneService), this);
            }
        }

        public void OnComponentRemoved(object sender, GameComponentCollectionEventArgs e)
        {
            if (e.GameComponent == this)
            {
                Game.Services.RemoveService(typeof(ISceneService));
                Game.Components.ComponentAdded -= this.OnComponentAdded;
                Game.Components.ComponentRemoved -= this.OnComponentRemoved;
            }
        }
    }
}
